<?php
// 应用公共文件

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

function parse_address($address)
{
    $address       = implode("", array_unique(explode("/", $address)));
    $apiUrl        = 'http://cloud.kuaidi100.com/api';
    $secret_key    = "hjHPKEHrb7PL5Tp41Q";
    $secret_secret = "0d8e4d1bdd81447ba4f15111c304df9c";
    $secret_code   = "0db4f037e2094f15a811261722e8a6e9";

    // 构造请求数据
    $data                = [
        'secret_key'  => $secret_key,
        'secret_code' => $secret_code,
    ];
    $data['secret_sign'] = strtoupper(md5($secret_key . $secret_secret));
    $data['content']     = $address;

    // 使用 cURL 发送请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 关闭SSL证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    // 解析响应
    $responseData = json_decode($response, true);
    if ($responseData['code'] === 200) {
        $xzq      = $responseData['data'][0]['xzq'];
        $province = $xzq['province'];
        $city     = $xzq['city'];
        $district = $xzq['district'];

        $arr      = [$province, $city, $district, "省", "市", "县"];
        $sub_area = $xzq['subArea'];
        foreach ($arr as $value) {
            $sub_area = str_replace($value, '', $sub_area);
        }
        $new_address = "中国" . $province . $city . $district . $sub_area;
        return $new_address;
    } else {
        return $address;
    }
}

function tecent_address_parse($address)
{
    $address_arr = explode("/", trim($address, "/"));
    $address     = implode("", array_unique($address_arr));
    // 云市场分配的密钥Id
    $secretId = 'AKIDg52k4i6biGX7i68ibB5imFL9yxki4u0NlDH9';
    // 云市场分配的密钥Key
    $secretKey = 'j40uw5ywvw9rAd5Gbyl3i6pC9l3Pnc1b8Q8vm1rl';
    $source    = 'market';

    // 签名
    $datetime = gmdate('D, d M Y H:i:s T');
    $signStr  = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
    $sign     = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
    $auth     = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);

    // 请求方法
    $method = 'GET';
    // 请求头
    $headers = array(
        'X-Source'      => $source,
        'X-Date'        => $datetime,
        'Authorization' => $auth,

    );
    // 查询参数
    $queryParams = array(
        'content' => $address,
    );
    // body参数（POST方法下）
    $bodyParams = array();
    // url参数拼接
    $url = 'https://service-6qbnpmw2-1300683954.gz.apigw.tencentcs.com/release/dizhi';
    if (count($queryParams) > 0) {
        $url .= '?' . http_build_query($queryParams);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
        return $k . ': ' . $v;
    }, array_values($headers), array_keys($headers)));
    if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
    }
    // 关闭SSL证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        \think\facade\Log::error("Error: " . curl_error($ch));
        curl_close($ch);
        return $address;
    } else {
        curl_close($ch);
        $data = json_decode($data, true);
        print_r($data);
        if ($data['code'] == 0) {
            $zxs      = ['北京', '天津', '上海', '重庆'];
            $xzq      = $data['result'];
            $province = $xzq['province'];
            $city     = $xzq['city'];
            $district = $xzq['area'];

            $arr = [$province, $city, $district];
            if (!empty($address_arr) && count($address_arr) > 1) {
                $sub_area = $address_arr[count($address_arr) - 2];
                $sub_area .= $address_arr[count($address_arr) - 1];
            } else {
                $sub_area = $xzq['street'];
            }
            foreach ($arr as $value) {
                $sub_area = str_replace($value, '', $sub_area);
            }
//            if (!empty($address_arr)) {
//                $target = $sub_area;
//                $last_str = $address_arr[count($address_arr) - 1];
//                $pos = strpos($last_str, $target);
//                if ($pos!== false) {
//                    $sub_area = substr($last_str, $pos);
//                }
//            }

            if (in_array($province, $zxs)) {
                $new_address = "中国" . $city . $district . $sub_area;
            } else {
                $new_address = "中国" . $province . $city . $district . $sub_area;
            }
            return $new_address;
        } else {
            return $address;
        }
    }

}

function baidu_address_parse($address, $access_token)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL            => "https://aip.baidubce.com/rpc/2.0/nlp/v1/address?access_token={$access_token}",
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_CUSTOMREQUEST  => 'POST',

        CURLOPT_POSTFIELDS => '{"text":"' . $address . '"}',

        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Accept: application/json'
        ),

    ));
    $response = curl_exec($curl);
    curl_close($curl);
//    print_r($response);
    $data = json_decode($response, true);
    if (isset($data['province'])) {
        $zhixia     = ['北京市', '天津市', '重庆市', '上海市'];
        $province   = $data['province'] ?? '';
        $city       = $data['city'] ?? '';
        $county     = $data['county'] ?? '';
        $town       = $data['town'] ?? '';
        $detail     = $data['detail'];
        $detail_arr = explode("/", $detail);
        $detail_arr = array_filter(array_unique($detail_arr));
        $detail     = implode("", $detail_arr);
        $detail     = str_replace($province, "", $detail);
        $detail     = str_replace($city, "", $detail);
        $detail     = str_replace($county, "", $detail);
        $detail     = str_replace("/", "", $detail);
        if (in_array($data['province'], $zhixia)) {
            $new_addr = '中国' . $city . $county . $town . $detail;
        } else {
            $new_addr = '中国' . $province . $city . $county . $town . $detail;
        }
        return $new_addr;
    } else {
        return $address;
    }
}

function getAccessToken()
{
    $api_key    = 'XU6d4C0ULIBq60epF6AIsHHD';
    $secret_key = 'cSemyVObGn7Yf9Ecrz1vX0GKpkWfL76m';
    $curl       = curl_init();
    $postData   = array(
        'grant_type'    => 'client_credentials',
        'client_id'     => $api_key,
        'client_secret' => $secret_key
    );
    curl_setopt_array($curl, array(
        CURLOPT_URL            => 'https://aip.baidubce.com/oauth/2.0/token',
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => http_build_query($postData)
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    $rtn = json_decode($response);
    return $rtn->access_token;
}


function doubao_parse_address($address) {

// 获取 API 密钥
    $apiKey = "b5de2a83-d71f-4e55-a623-df65dd1f8f42";
    if (!$apiKey) {
        die("ARK_API_KEY environment variable is not set.\n");
    }

// 请求的 URL
    $baseUrl = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";

// 请求的头信息
    $headers = [
        "Content-Type: application/json",
        "Authorization: Bearer " . $apiKey
    ];
    $content = "请按照 “中国 xxx 省 xxx 市 xxx 区 + 详细地址” 的格式，对以下地址进行解析，详细地址不要包含省市区。按格式只返回一个你认为正确的地址信息，不要返回其他任何的信息";
    $content = "你是一个专业的中文地址解析助手。请将用户输入的非结构化地址转换为以下格式：
中国 + 省级行政区全称 + 地级市全称 + 市辖区全称 + 详细地址。规则如下：
1. 自动补全省份/城市名称
2. 修正错别字，忽略除地址以外的信息，不要有重复的省、市、区
3. 解析出多个地址只返回一个最终结果,不要返回任何关于地址分析推理的相关话语";
// 标准请求数据
    $standardData = [
        "model"    => "doubao-1-5-lite-32k-250115",
        "messages" => [
            [
                "role"    => "system",
                "content" => $content
            ],
            [
                "role"    => "user",
                "content" => "$address"
            ],
        ]
    ];

    // 发起标准请求
    $ch = curl_init($baseUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);     // 不检查主机名匹配
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($standardData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10000);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "ChatCompletion error: " . curl_error($ch) . "\n";
        curl_close($ch);
        return "";
    } else {
        curl_close($ch);
        $result = json_decode($response, true);
        if (isset($result['choices'][0]['message']['content'])) {
            $info = explode("\n", $result['choices'][0]['message']['content']);
            if (isset($info[0])) {
                return $info[0];
            } else {
                return "";
            }
        } else {
            return "";
        }
    }
}



function doubao_parse_name($name) {

// 获取 API 密钥
    $apiKey = "b5de2a83-d71f-4e55-a623-df65dd1f8f42";
    if (!$apiKey) {
        die("ARK_API_KEY environment variable is not set.\n");
    }

// 请求的 URL
    $baseUrl = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";

// 请求的头信息
    $headers = [
        "Content-Type: application/json",
        "Authorization: Bearer " . $apiKey
    ];

// 标准请求数据
    $standardData = [
        "model"    => "doubao-1-5-lite-32k-250115",
        "messages" => [
            [
                "role"    => "system",
                "content" => "请按以下要求处理姓名：
                1、删除所有重复项。
                2、返回名字正确的顺序，姓氏在前，名字在后。"
            ],
            [
                "role"    => "user",
                "content" => $name
            ]
        ]
    ];

    // 发起标准请求
    $ch = curl_init($baseUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略证书验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);     // 不检查主机名匹配
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($standardData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10000);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "ChatCompletion error: " . curl_error($ch) . "\n";
        curl_close($ch);
        return "";
    } else {
        curl_close($ch);
        $result = json_decode($response, true);
        if (isset($result['choices'][0]['message']['content'])) {
            $info = explode("\n", $result['choices'][0]['message']['content']);
            if (isset($info[0])) {
                return $info[0];
            } else {
                return "";
            }
        } else {
            return "";
        }

    }
}
